#include "bookview.h"
#include "ui_bookview.h"

BookView::BookView(QWidget *parent) :
        AbstractView(parent),
        m_ui(new Ui::BookView),pageLeft(new BookPage),pageRight(new BookPage),bookData(0)
{
    m_ui->setupUi(this);

    mainLayout = new QGridLayout;
    mainLayout->addWidget(pageLeft, 0, 0);
    mainLayout->addWidget(pageRight, 0, 1);
    setLayout(mainLayout);

    mainLayout->setSizeConstraint(QLayout::SetMinimumSize);
    index = 0;
}
void BookView::load(const QString &url){
    BookDataBuilder* builder=0;
    if(url.endsWith(".txt",Qt::CaseInsensitive)){
        builder =  new TXTBookDataBuilder(url);
        builder->parse();
    }else{
        return;
    }
    bookData = builder->getBookData();
    index = 0;
    show(index);
}
void BookView::showNext(){
    if(index+2<bookData->getContents()->count())index+=2;
    show(index);
}
void BookView::showPrevious(){
    if(index-2>=0)index-=2;
    show(index);
}

void BookView::show(int index){
    QVector<QString>* cont = bookData->getContents();
    if(index<cont->count()){
        pageLeft->load(cont->at(index),index);
    }else{
        return;
    }
    if(index+1<cont->count()){
        pageRight->load(cont->at(index+1),index+1);
    }else{
        pageRight->load("",index+1);
    }
}
void BookView::preview(){
    pageRight->preview();
}
BookView::~BookView()
{
    delete m_ui;
    delete pageLeft;
    delete pageRight;
    delete bookData;
}

void BookView::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
